import { v4 as uuidv4 } from "uuid";
export default class myWebSocket {
  constructor(url) {
    // 指定ws的地址,并生成客户端id
    this.url = url || `ws://localhost:3000?uid=${uuidv4()}`;
    this.socket = null; // 实例化的ws对象
  }

  connect(cb) {
    // console.log({ url: this.url });
    this.socket = new WebSocket(this.url);

    // 监听连接是否正常打开
    this.socket.onopen = function (e) {
      console.log("连接成功");
    };
    // 监听错误
    this.socket.onerror = (e) => {
      console.error("连接错误", e);
      this.close();
    };
    // 接收服务端推送的消息
    this.socket.onmessage = (wsObj) => {
      cb?.(JSON.parse(wsObj.data));
    };
  }
  send(msg) {
    // 发消息
    this.socket.send(JSON.stringify(msg));
  }
  close() {
    // 使用close去关闭已经开启的WebSocket服务
    this.socket.close();
    this.socket = null; // 回归默认值
  }
}
